import React, { useState } from "react";
import { TextField, PrimaryButton, Stack } from "@fluentui/react";
import axios from "axios";
import qs from "qs";
import { stackStyles, stackTokens, columnProps } from "./stack-config";

export function Register() {
  const [username, setUsername] = useState("");
  const [password, setPassword] = useState("");
  const [disabled, setDisabled] = useState(false);

  function handleUsernameChange(_e: unknown, newValue?: string) {
    setUsername(newValue ?? "");
  }
  function handlePasswordChange(_e: unknown, newValue?: string) {
    setPassword(newValue ?? "");
  }
  function submit() {
    setDisabled(true);
    axios({
      method: "POST",
      url: "reg.asp",
      headers: { "Content-Type": "application/x-www-form-urlencoded" },
      data: qs.stringify({
        username,
        password,
      }),
    })
      .then((res) => {
        if (res.data === "yes") {
          alert("添加用户成功！");
        } else {
          alert(`添加用户失败！原因：${JSON.stringify(res.data)}`);
        }
      })
      .catch((e) => {
        alert(`添加用户失败！原因：${JSON.stringify(e)}`);
      })
      .finally(() => {
        setDisabled(false);
      });
    console.log(username, password);
  }
  return (
    <Stack horizontal tokens={stackTokens} styles={stackStyles}>
      <Stack {...columnProps}>
        <TextField
          name="username"
          label="用户名"
          required
          onChange={handleUsernameChange}
        />
        <TextField
          name="password"
          label="密码"
          required
          type="password"
          canRevealPassword
          onChange={handlePasswordChange}
        />
        <PrimaryButton
          text="注册"
          disabled={disabled}
          onClick={submit}
          style={{ marginTop: 10, marginBottom: 50 }}
        />
      </Stack>
    </Stack>
  );
}
